﻿using LiteDB;

namespace VIA.Project.Domain.Services
{
    public interface ILocalDatabaseService
    {
        ILiteCollection<T> GetCollection<T>();
        ILiteCollection<T> GetCollection<T>(string name);
        void Close();
        string DatabasePath { get; }
    }

    internal class LocalDatabaseService : ILocalDatabaseService
    {
        private LiteDatabase _db;

        public string DatabasePath { get; private set; }

        public LocalDatabaseService()
        {
            DatabasePath = GetDatabasePath();
            _db = GetDatabse(DatabasePath);
        }

        private LiteDatabase GetDatabse(string path)
        {
            BsonMapper mapper = new BsonMapper();
            var db = new LiteDatabase(path, mapper);
            return db;
        }

        private string GetDatabasePath()
        {
            var path = Environment.CurrentDirectory;
            path = Path.Combine(path, "Data");
            Directory.CreateDirectory(path);
            path = Path.Combine(path, "data.db");
            return path;
        }

        public void Close()
        {
            _db.Dispose();
        }

        public ILiteCollection<T> GetCollection<T>()
        {
            var list = _db.GetCollection<T>();
            return list;
        }

        public ILiteCollection<T> GetCollection<T>(string name)
        {
            var list = _db.GetCollection<T>(name);
            return list;
        }
    }
}
